package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LooperEx extends Activity {
	TextView mainTv;
	TextView backTv;
	EditText mEdit;
	int mainValue;
	CalThread thread;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.ch19_loopertest);
		
		mainTv = (TextView) findViewById(R.id.ch19_looper_mainvalue);
		backTv = (TextView) findViewById(R.id.ch19_looper_backvalue);
		mEdit = (EditText) findViewById(R.id.ch19_looper_number);
		
		thread = new CalThread(mMainHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v){
		Message msg = null;
		switch(v.getId()){
		case R.id.ch19_looper_increase:
			mainValue++;
			mainTv.setText("MainValue : " + mainValue);
			break;
		case R.id.ch19_looper_square:
			msg = Message.obtain(thread.mBackHandler, 0, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
		case R.id.ch19_looper_root:
			msg = Message.obtain(thread.mBackHandler, 1, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
		}
		
	}
	
	Handler mMainHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				backTv.setText("Square Result : " + msg.arg1);
				break;
			case 1:
				backTv.setText("Root Result : " + ((Double)msg.obj).doubleValue());
				break;
			}
		};
	};
}

class CalThread extends Thread {
	Handler mMainHandler;
	Handler mBackHandler;

	public CalThread(Handler mMainHandler) {
		super();
		this.mMainHandler = mMainHandler;
	}

	public void run() {
		Looper.prepare();
		mBackHandler = new Handler() {
			public void handleMessage(Message msg) {
				Message retMsg = Message.obtain();
				switch (msg.what) {
				case 0:
					retMsg.what = 0;
					retMsg.arg1 = msg.arg1 * msg.arg1;
					break;
				case 1:
					retMsg.what = 1;
					retMsg.obj = new Double(Math.sqrt(msg.arg1));
					break;
				}
				mMainHandler.sendMessage(retMsg);
			}
		};
		Looper.loop();
	}

}
